﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Hosting;
using System.Web.Mvc;
using System.Web.UI.WebControls;
using GWEB.WebBase.Data;
using GWEB.WebBase.Entity;
using GWEB.WebBase.Utility;
using GWEB.WebFrame.Public;
using Newtonsoft.Json;

namespace GWEB.WebFrame.Contract
{
    public class ContractListController : PageInfoBase
    {        
        [ActionFilter(IsLogin = true)]
        public ActionResult Index(String id, String keyCode)
        {
            DataRow drUser = BasePage.GetUser(Session);
            String leagueId = Fun.cString(drUser["LeagueId"].ToString());
            string sql = string.Format("select * from cu_contract_class where LeagueId='{0}'", leagueId);
            ViewBag.SetmealType = BasePage.bd.ExecuteTable(sql);
            sql = string.Format("select did,dname,typeid,helpcode from tb_sys_dictionary where typeid='D17'");
            ViewBag.Gift = BasePage.bd.ExecuteTable(sql);
            sql = string.Format("select did,dname,typeid from tb_sys_dictionary where typeid='D16'");
            ViewBag.AccountMode = BasePage.bd.ExecuteTable(sql);
         
            return Load("ContractList", "Contract/ContractList", id, keyCode);
        }
        [ActionFilter(IsJson = true)]
        public JsonResult Data(String type, String id, String keyCode,String Tel,String Khid)
        { 
                DataRow drUser = BasePage.GetUser(Session);
                String leagueId = Fun.cString(drUser["LeagueId"].ToString());
                PageInfo pg = isBrowse(type, id, keyCode);
            if (pg == null)
            {
                return BasePage.Json(ResultData.Error(WebMessage.NoBrowse));
            }
            String sql = @"select  cu_Customers.id ,'0' LinkCustId,CustName,ChildName,CustTel, cu_Customers.LinkName, cu_Customers.LinkRelation,LatelyReceId,Sex,cusImage,isnull(address,'未设置') address, 
                   isnull((select SUM(account) je from cu_Account where cid=cu_Customers.id  and FlowingType in ('00101001','00201001') and state=2),0) je,
isnull((select CreateUser.sshowname from  tb_sys_users CreateUser where CreateUser.iuserid  = cu_Customers.LatelyReceId),'未设置') AchievementName
                 from cu_Customers 
                
                 where CustTel like '%" + keyCode+ @"%' and  cu_Customers.LeagueId='"+ leagueId + "' ";
            BasePage.bd.ColumnNameToLower = false;
            String str = JsonConvert.SerializeObject(BasePage.bd.ExecuteTable(sql));
            BasePage.bd.ColumnNameToLower = true;
            List<Dictionary<String, Object>> data = JsonConvert.DeserializeObject<List<Dictionary<String, Object>>>(str);
            return BasePage.Json(ResultData.OK(data));

        }
        [ActionFilter(IsJson = true)]
        public JsonResult ContractImage(String type, String id, String keyCode)
        {
            DataRow drUser = BasePage.GetUser(Session);
            String leagueId = Fun.cString(drUser["LeagueId"].ToString());
            PageInfo pg = isBrowse(type, id, keyCode);
            if (pg == null)
            {
                return BasePage.Json(ResultData.Error(WebMessage.NoBrowse));
            }
            String sql = @" select cu_Contract_Image.*,cu_Contract.state zt from cu_Contract_Image left join cu_Contract on Cu_contract.id=contractId  where contractId={0}";
            BasePage.bd.ColumnNameToLower = false;
            String str = JsonConvert.SerializeObject(BasePage.bd.ExecuteTable(string.Format(sql,id)));
            BasePage.bd.ColumnNameToLower = true;
            List<Dictionary<String, Object>> data = JsonConvert.DeserializeObject<List<Dictionary<String, Object>>>(str);
            return BasePage.Json(ResultData.OK(data));

        }
        [ActionFilter(IsJson = true)]
        public JsonResult IsContractNumber(String type, String id, String keyCode,string ConNum)
        {
            DataRow drUser = BasePage.GetUser(Session);
            String leagueId = Fun.cString(drUser["LeagueId"].ToString());
            PageInfo pg = isBrowse(type, id, keyCode);
            if (pg == null)
            {
                return BasePage.Json(ResultData.Error(WebMessage.NoBrowse));
            }
            String sql = @" select isnull(COUNT(*),0) sl from cu_Contract where  contractNumber='{0}' and  leagueId="+leagueId;
            BasePage.bd.ColumnNameToLower = false;
            String str = JsonConvert.SerializeObject(BasePage.bd.ExecuteTable(string.Format(sql, ConNum)));
            BasePage.bd.ColumnNameToLower = true;
            List<Dictionary<String, Object>> data = JsonConvert.DeserializeObject<List<Dictionary<String, Object>>>(str);
            return BasePage.Json(ResultData.OK(data));

        }
        [ActionFilter(IsJson = true)]
        public JsonResult CourseList(String type, String id, String keyCode, string Cid, string ContractId)
        {
            DataRow drUser = BasePage.GetUser(Session);
            String leagueId = Fun.cString(drUser["LeagueId"].ToString());
            PageInfo pg = isBrowse(type, id, keyCode);
            if (pg == null)
            {
                return BasePage.Json(ResultData.Error(WebMessage.NoBrowse));
            }
            String sql = @"
select cu_teachercourse_sign.id,CONVERT(varchar(10),Godate,120) Godate,CourseName,isnull(DecClass,0) DecClass,IsAuditions,cu_Contract.SetmealName+'【'+cu_Contract.contractNumber+'】' contractName,CONVERT(varchar(10),surplusnumber)+'-'+convert(varchar(10),GiveCourseNumber) surNumber,
case  cu_teachercourse_sign.state when 0 then '已报名' when '1' then '已签到' when '3' then '旷课' when 4 then '已请假' end stateName
 from cu_teachercourse_sign 
left join
cu_TeacherCourse on cu_TeacherCourse.id=Tid
left join
cu_Contract on cu_Contract.id=ContractId
where cu_teachercourse_sign.Cid={0} and  cu_teachercourse_sign.LeagueId={1} ";
            BasePage.bd.ColumnNameToLower = false;
            DataTable dtall = BasePage.bd.ExecuteTable(string.Format(sql,Cid,leagueId));
            Dictionary<String, Object> data = new Dictionary<string, object>();
            data.Add("count", dtall.Rows.Count);
            int PageIndex = int.Parse(Request.QueryString["page"]);
            int PageSize = int.Parse(Request.QueryString["limit"]);
            DataTable dt = GetPagedTable(dtall, PageIndex, PageSize);
            String str = JsonConvert.SerializeObject(dt);
            BasePage.bd.ColumnNameToLower = true;
            List<Dictionary<String, Object>> data1 = JsonConvert.DeserializeObject<List<Dictionary<String, Object>>>(str);
            data.Add("data", data1);
            return BasePage.Json(ResultData.OK(data));

        }
        [ActionFilter(IsJson = true)]
        public JsonResult LinkList(String type, String id, String keyCode, string Cid, string ContractId)
        {
            DataRow drUser = BasePage.GetUser(Session);
            String leagueId = Fun.cString(drUser["LeagueId"].ToString());
            PageInfo pg = isBrowse(type, id, keyCode);
            if (pg == null)
            {
                return BasePage.Json(ResultData.Error(WebMessage.NoBrowse));
            }
            String sql = @"
select cu_Contract_Customer.id,cu_Contract_Customer.id,LinkName,KidsName,Sex,LinkTel from cu_Contract_Customer
left join 
cu_Cus_contacts on cu_Cus_contacts.Cid= cu_Contract_Customer.LinkCustId
where cu_Contract_Customer.contractId={0}  and cu_Contract_Customer.CustId={1} ";
            BasePage.bd.ColumnNameToLower = false;
            DataTable dtall = BasePage.bd.ExecuteTable(string.Format(sql, ContractId,Cid));
            Dictionary<String, Object> data = new Dictionary<string, object>();
            data.Add("count", dtall.Rows.Count);
            int PageIndex = int.Parse(Request.QueryString["page"]);
            int PageSize = int.Parse(Request.QueryString["limit"]);
            DataTable dt = GetPagedTable(dtall, PageIndex, PageSize);
            String str = JsonConvert.SerializeObject(dt);
            BasePage.bd.ColumnNameToLower = true;
            List<Dictionary<String, Object>> data1 = JsonConvert.DeserializeObject<List<Dictionary<String, Object>>>(str);
            data.Add("data", data1);
            return BasePage.Json(ResultData.OK(data));

        }
        [ActionFilter(IsLogin = true)]
        public JsonResult DelImage(String id, String keyCode )
        {

            BaseData bd = new BaseData();
            string UserId = BasePage.GetUserId(Session);
            String sql = " delete cu_Contract_image where id={0}";


            bool t = bd.ExecuteSQL(string.Format(sql, id));
            if (t)
                return BasePage.Json(ResultData.Code("0000", WebMessage.SaveSuccess));
            else
                return BasePage.Json(ResultData.Code("0001", WebMessage.SaveFailure));
        }
        [ActionFilter(IsLogin = true)]
        public JsonResult DelContract(String id, String keyCode)
        {

            BaseData bd = new BaseData();
            string UserId = BasePage.GetUserId(Session);
            
            String[] sql = new String[6];
            int Cid = 0;
            int htsl = 0;
            decimal djje = 0;
            String StrSql = @"select cu_contract.Cid,djje,htsl from cu_contract
            left join
            (select ISNULL(sum(account),0) djje, {0} ContractId from cu_Account where cu_Account.ContractId = '{0}' and FlowingType in ('00101001', '00201001') and state = '3') a on a.ContractId = id
             left join
            (select isnull(COUNT(*),0) htsl,Cid from cu_contract where(isnull(SurplusNumber,0)-isnull(GiveCourseNumber, 0) > 0 or isnull(CourseEnd,'2099-12-31')> GETDATE()) group by Cid) b on b.Cid = cu_contract.Cid
             where id = {0}";
            DataTable dt = BasePage.bd.ExecuteTable(string.Format(StrSql,id));
            if (dt != null)
            {
                Cid = int.Parse(dt.Rows[0]["Cid"].ToString());
                htsl = int.Parse(dt.Rows[0]["htsl"].ToString());
                djje=decimal.Parse(dt.Rows[0]["djje"].ToString());
            }

            sql[0] = " delete cu_Contract where id={0}";
            sql[1] = "delete cu_Contract_Image where contractId={0}";
            sql[2] = "delete cu_Contract_Customer where contractId={0}";
            sql[3] = "delete  cu_Account where contractId={0} and FlowingType in ('00102001','00202001')  and state='0' ";
            sql[4] = "update  cu_Account set contractId=null,state=2 where contractId={0} and FlowingType in ('00101001','00201001')  and state='3' ";
            if(htsl==1)
            { 
                if(djje>0)
                   sql[5] = "update cu_Customers set  CustState='5' where id=  "+Cid.ToString();
                else
                  sql[5] = "update cu_Customers set  CustState='3' where id=" + Cid.ToString();
            }
            for (int i = 0; i <= 4; i++)
                sql[i] = string.Format(sql[i], id);

            bool t = bd.ExecuteSQL(sql);

            if (t)
                return BasePage.Json(ResultData.Code("0000", WebMessage.SaveSuccess));
            else
                return BasePage.Json(ResultData.Code("0001", WebMessage.SaveFailure));
        }
        [ActionFilter(IsLogin = true)]
        public JsonResult DelLink(String id, String keyCode)
        {

            BaseData bd = new BaseData();
            string UserId = BasePage.GetUserId(Session);
            String sql = " delete cu_Contract_Customer where id={0}";


            bool t = bd.ExecuteSQL(string.Format(sql, id));
            if (t)
                return BasePage.Json(ResultData.Code("0000", WebMessage.SaveSuccess));
            else
                return BasePage.Json(ResultData.Code("0001", WebMessage.SaveFailure));
        }
        [ActionFilter(IsLogin = false)]
        public JsonResult UpdateState(String id, String keyCode, String state)
        {
            if (!Fun.IDVerify(id, keyCode))
                return BasePage.Json(ResultData.Code("0001", "您没有权限"));

            BaseData bd = new BaseData();
            string UserId = BasePage.GetUserId(Session);
            String sql = "update cu_Contract set state={0},auditingid='" + UserId + "',auditingdate='" + System.DateTime.Now.ToString() + "' where id={1}";


            bool t = bd.ExecuteSQL(string.Format(sql, state, id));
            if (t)
                return BasePage.Json(ResultData.Code("0000", WebMessage.SaveSuccess));
            else
                return BasePage.Json(ResultData.Code("0001", WebMessage.SaveFailure));
        }
        [ActionFilter(IsLogin = true)]
        public JsonResult DjData(String type, String id, String keyCode, string Cid,string ContractId)
        {
            DataRow drUser = BasePage.GetUser(Session);
            String leagueId = Fun.cString(drUser["LeagueId"].ToString());
            PageInfo pg = isBrowse(type, id, keyCode);
            if (pg == null)
            {
                return BasePage.Json(ResultData.Error(WebMessage.NoBrowse));
            }
            String sql = @"select  cu_Account.id,D16.dname FlowingName,D15.dname ModeName,Account,convert(varchar(10),ADate,120) ADate,isnull(sshowname,'未设置') AchName,flowingtype,cu_Account.state,cu_Account.isReturn,isnull(cu_Account.ContractId,-1) ContractId,isnull(cu_Account.activityId,-1) activityId ,isnull(cu_Account.FollowUPId,-1) FollowUPId,
 case when  cu_Contract.CourseEnd is null then 0  when  cu_Contract.CourseEnd>GETDATE() then 0 else  1 end htstate,  cu_Contract.SetmealName+'【'+cu_Contract.contractNumber+'】' SetmealName,               
case cu_Account.state when 0 then '未入帐' when 1 then '已提交未审核' when 2 then '已入帐' when 3 then '已使用' when 4 then '已作废' end stateName 
             from cu_Account
             left join
             tb_sys_users on  iuserid = AchievementId
             left join
             tb_sys_dictionary D16 on d16.did = AccountMode and d16.typeid = 'D16'
             left join
             tb_sys_dictionary D15 on d15.did = FlowingType and d15.typeid = 'D15'
             left join 
             cu_Contract on cu_Contract.id=cu_Account.ContractId
               where  cu_Account.cid = '" + Cid + "'  and cu_Account.LeagueId='" + leagueId + "' and cu_Account.ContractId>0 order by  cu_Account.id desc";
            BasePage.bd.ColumnNameToLower = false;
            DataTable dtall = BasePage.bd.ExecuteTable(sql);
            Dictionary<String, Object> data = new Dictionary<string, object>();
            data.Add("count", dtall.Rows.Count);
            int PageIndex = int.Parse(Request.QueryString["page"]);
            int PageSize = int.Parse(Request.QueryString["limit"]);
            DataTable dt = GetPagedTable(dtall, PageIndex, PageSize);
            String str = JsonConvert.SerializeObject(dt);
            BasePage.bd.ColumnNameToLower = true;
            List<Dictionary<String, Object>> data1 = JsonConvert.DeserializeObject<List<Dictionary<String, Object>>>(str);
            data.Add("data", data1);
            return BasePage.Json(ResultData.OK(data));

        }
        public DataTable GetPagedTable(DataTable dt, int PageIndex, int PageSize)//PageIndex表示第几页，PageSize表示每页的记录数
        {
            if (PageIndex == 0)
                return dt;//0页代表每页数据，直接返回

            DataTable newdt = dt.Copy();
            newdt.Clear();//copy dt的框架

            int rowbegin = (PageIndex - 1) * PageSize;
            int rowend = PageIndex * PageSize;

            if (rowbegin >= dt.Rows.Count)
                return newdt;//源数据记录数小于等于要显示的记录，直接返回dt

            if (rowend > dt.Rows.Count)
                rowend = dt.Rows.Count;
            for (int i = rowbegin; i <= rowend - 1; i++)
            {
                DataRow newdr = newdt.NewRow();
                DataRow dr = dt.Rows[i];
                foreach (DataColumn column in dt.Columns)
                {
                    newdr[column.ColumnName] = dr[column.ColumnName];
                }
                newdt.Rows.Add(newdr);
            }
            return newdt;
        }
        [ActionFilter(IsLogin = true)]
        public JsonResult RyHtData(String type, String id, String keyCode, string Cid)
        {
            DataRow drUser = BasePage.GetUser(Session);
            String leagueId = Fun.cString(drUser["LeagueId"].ToString());
            PageInfo pg = isBrowse(type, id, keyCode);
            if (pg == null)
            {
                return BasePage.Json(ResultData.Error(WebMessage.NoBrowse));
            }
            String sql = @" select id, contractNumber,SetmealName,ContractPrice,DisPrice,convert(varchar(10),CreateDate,120) CreateDate,isnull(sshowname,'未设置') AchName,
                 case state when 0 then '未提交' when 1 then '未审核' when 2 then '已审核' when 3 then '3审核未通过'  end stateName,
                    case status when 0 then '已登记未收费' when 1 then '已登记费用未入账' when 5 then '已登记退费未出账' when 6 then '已退费' else '已入账' end statusName,
                   convert(varchar(10), isnull(Htje,0))+'/'+convert(varchar(10),isnull(DisPrice,0))+'/'+convert(varchar(10),isnull(ContractPrice,0)) je,
                   convert(varchar(10), Constart,120)+'至'+  convert(varchar(10), ConEnd,120) ConDate, case when CourseStart is null  then '未设置' else   convert(varchar(10),CourseStart,120)+'至'+  convert(varchar(10), CourseEnd,120) end CourseDate,
                        '合同编号：'+ contractNumber+'套餐名称：' +SetmealName+'合同金额：'+CONVERT(varchar(10),contractprice)+' 实收：'+CONVERT(varchar(10),DisPrice)+' 订金：'+CONVERT(varchar(10),DjWsyJe)+' 已收:'+convert(varchar(10),isnull(Htje,0))+'本次应收：'+convert(varchar(10),DisPrice-isnull(DjWsyJe,0)-isnull(htje,0))  Htxx,DisPrice-isnull(DjWsyJe,0)-isnull(htje,0) Htysje,isnull(htje,0) HtSfje
               
                    from cu_Contract
                left join
             tb_sys_users on iuserid = AchievementId 
             left join
                (select cid, SUM(case when FlowingType in ('00101001','00201001') then Account else 0 end) Djje,
              sum(case when   cu_Account.state<2 and  FlowingType in ('00101001','00201001') then Account else 0 end ) DjWrzJe,  
               sum(case when   cu_Account.state=2 and  FlowingType in ('00101001','00201001') then Account else 0 end ) DjWsyJe,  
               sum(case when   cu_Account.state=3  and  FlowingType in ('00101001','00201001')then Account else 0 end ) DjYsyJe,  
                 sum(case when   cu_Account.state=4  and  FlowingType in ('00101001','00201001')then Account else 0 end ) DjZfJe
                
              from cu_Account   group by cid) Dj  on Dj.cid=cu_Contract.Cid  
             left join 
              (select cid,ContractId,SUM(Account) Htje            
              from cu_Account where (cu_Account.state<=2 and  FlowingType in ('00102001','00202001')) or (cu_Account.state=3 and  FlowingType in ('00101001','00201001')) group by cid,ContractId) Ht  on Ht.ContractId=cu_Contract.id  
           where  cu_Contract.cid = '" + Cid + "'  and cu_Contract.LeagueId='" + leagueId + "' order by id desc ";
            BasePage.bd.ColumnNameToLower = false;
            DataTable dtall = BasePage.bd.ExecuteTable(sql);
            Dictionary<String, Object> data = new Dictionary<string, object>();
            data.Add("count", dtall.Rows.Count);
            int PageIndex = int.Parse(Request.QueryString["page"]);
            int PageSize = int.Parse(Request.QueryString["limit"]);
            DataTable dt = GetPagedTable(dtall, PageIndex, PageSize);
            String str = JsonConvert.SerializeObject(dt);
            BasePage.bd.ColumnNameToLower = true;
            List<Dictionary<String, Object>> data1 = JsonConvert.DeserializeObject<List<Dictionary<String, Object>>>(str);
            data.Add("data", data1);
            return BasePage.Json(ResultData.OK(data));

        }

        [ActionFilter(IsLogin = true)]
        public JsonResult RyHdData(String type, String id, String keyCode, string Cid)
        {
            DataRow drUser = BasePage.GetUser(Session);
            String leagueId = Fun.cString(drUser["LeagueId"].ToString());
            PageInfo pg = isBrowse(type, id, keyCode);
            if (pg == null)
            {
                return BasePage.Json(ResultData.Error(WebMessage.NoBrowse));
            }
            String sql = @"select id,DecPrice,convert(varchar(10),CreateDate,120) CreateDate,(select ActivityName from cu_Activity where cu_Activity.id=cu_Activity_SignUp.ActivityId)  ActivityName,
               case   when state<2 then '未收费' when state=2 then '已确认未入账' when state>2 and state<5 then '已缴费' when state=6 then '已退费' else '已提交退费审请'  end stateName,  	
                  '活动金额：'+ convert(varchar(10),Decprice)+' 已收:'+convert(varchar(10),isnull(Hdje,0))+'本次应收：'+convert(varchar(10),Decprice-isnull(Hdje,0))   Hdxx,Decprice-isnull(Hdje,0) Hdysje
            
                from cu_Activity_SignUp
                 left join 
              (select cid,activityId,SUM(case when FlowingType in ('00103001','00203001') and cu_Account.state<>4 then Account else 0 end) Hdje            
              from cu_Account   group by cid,activityId) Hd  on Hd.activityId=cu_Activity_SignUp.id 
       
           where   cu_Activity_SignUp.cid = '" + Cid + "'  and cu_Activity_SignUp.LeagueId='" + leagueId + "' order by id desc ";
            BasePage.bd.ColumnNameToLower = false;
            DataTable dtall = BasePage.bd.ExecuteTable(sql);
            Dictionary<String, Object> data = new Dictionary<string, object>();
            data.Add("count", dtall.Rows.Count);
            int PageIndex = int.Parse(Request.QueryString["page"]);
            int PageSize = int.Parse(Request.QueryString["limit"]);
            DataTable dt = GetPagedTable(dtall, PageIndex, PageSize);
            String str = JsonConvert.SerializeObject(dt);
            BasePage.bd.ColumnNameToLower = true;
            List<Dictionary<String, Object>> data1 = JsonConvert.DeserializeObject<List<Dictionary<String, Object>>>(str);
            data.Add("data", data1);
            return BasePage.Json(ResultData.OK(data));

        }
        protected override void FieldEditInit(DataRow data)
        {

            ViewBag.Lx = 1;
            ViewBag.Customer = 0;
            string sql = @"       select case when CustName is null then '' else  '宝宝姓名:'+ CustName end +case when ChildName is null then '' else '小名:'+ ChildName end +case when CustTel is null then '' else  '联系方式:'+ CustTel end+ case when linkname is null then '' else  '联系人:'+ linkname end khxx  from cu_Contract
                left join cu_Customers on cu_Customers.id=cu_Contract.Cid
                 where cu_Contract.id={0} ";
            DataTable dt = BasePage.bd.ExecuteTable(string.Format(sql, data["id"]));
            if (dt != null)
                ViewBag.Khxx = dt.Rows[0]["khxx"].ToString();
            else
                ViewBag.Khxx = "";
            base.FieldEditInit(data);
        }

        protected override void FieldAddInit(DataRow data)
        {
            ViewBag.Lx = 0;
            data["CreateId"] = BasePage.GetUserId(Session);
            DataRow drUser = BasePage.GetUser(Session);
            String leagueId = Fun.cString(drUser["LeagueId"].ToString());
            data["LeagueId"] = leagueId;
            data["contracttype"] = "新签约";
            data["SetmealId"] = 0;
            data["GiveCourseNumber"] = 0;
            data["Gift1"] = "";
            data["cid"] = "-1";
            data["Gift2"] = "";
            data["Gift3"] = "";
            data["state"] = 0;
            data["status"] =0;
            int Cid = 0;
            data["guid"] = Guid.NewGuid().ToString("N");
            try
            { Cid = int.Parse(Request.QueryString["cid"]); }
            catch { };
            if (Cid > 0)
            {
                try
                {
                    data["cid"] = Cid.ToString();
                   
                }
                catch
                {
                   

                }
                data["guid"] = Request.QueryString["guid"];
            }
            ViewBag.Customer = Cid;

            base.FieldAddInit(data);
        }
        protected override SqlState SqlExecute(BaseData bd, String id, Dictionary<String, Object> data)
        {
            String ImageUrl = data["ImageUrl"].ToString();
            String ImageName = data["ImageName"].ToString();          
            String LinkCustId = data["LinkCustId"].ToString();
            data.Remove("ImageUrl");
            data.Remove("ImageName");        
            data.Remove("LinkCustId");
            //增加时取序列，修改是不取序列，否则会引发错误	
            string[] strImage = ImageUrl.Split(','); //字符串转数组
            string[] strImageName = ImageName.Split(','); //字符串转数组
       
            string[] strLinkId = LinkCustId.Split(','); //字符串转数组
            String[] sql = new String[4+strImage.Length + strLinkId.Length];
            decimal ssje = 0, decje = 0;
            string cid = data["Cid"].ToString();
            string strSql = "select isnull(sum(Account),0) je from cu_Account where cid={0}  and (FlowingType in ('00101001','00201001') and state=2 or guid='{1}') ";
            DataTable dt = BasePage.bd.ExecuteTable(string.Format(strSql, cid, data["guid"].ToString()));

            if (dt != null)
            {
                ssje = decimal.Parse(dt.Rows[0]["je"].ToString());
            }
            decje = decimal.Parse(data["DisPrice"].ToString());
            if (ssje >= decje)
                data["status"] = "1";

            sql[0] = BaseData.MapToSql("cu_Contract", "id", id, data);
            int i = 0;
            int SqlIndex = 0;
            for (i = 0; i < strImage.Length; i++)
            {
                if (strImage[i]!="")
                {
                    SqlIndex += 1;
                sql[SqlIndex] = "insert into  cu_Contract_Image(contractId,ImageUrl,ImageName) values([id],'" + strImage[i] + "','" + strImageName[i] + "')"; }
            }
            int j = 0;
            for (j = 0; j < strLinkId.Length; j++)
            {
                if (strLinkId[j] != "")
                {
                    SqlIndex += 1;
                    sql[SqlIndex] = "insert into cu_Contract_Customer(contractId,CustId,LinkCustId) values([id],'" + data["Cid"].ToString() + "','" + strLinkId[j] + "')";
                }
            }
           
            string AccountSql = "update cu_Account set ContractId=[id] where guid='{0}'";
            sql[SqlIndex + 1] = string.Format(AccountSql, data["guid"].ToString());
            sql[SqlIndex + 2] = string.Format("update cu_Account set state='3', ContractId=[id] where  cid={0}  and FlowingType in ('00101001','00201001') and state=2 ", cid);
            sql[SqlIndex + 3] = string.Format("update cu_Customers set CustState='6' where  id={0}", cid);
            bool t = bd.ExecuteSQL(sql, -1, "cu_Contract", "id", id);
            return t ? SqlState.True : SqlState.False;
        }
        [ActionFilter(IsLogin = false)]
        public JsonResult SetmealType(String type, String id, String keyCode)
        {
            DataRow drUser = BasePage.GetUser(Session);
            String leagueId = Fun.cString(drUser["LeagueId"].ToString());
            PageInfo pg = isBrowse(type, id, keyCode);
            if (pg == null)
            {
                return BasePage.Json(ResultData.Error(WebMessage.NoBrowse));
            }
            String sql = "select *,case isclasshour when 1 then classhournumber else hournumber end number from cu_contract_class where LeagueId='"+ leagueId + "' and id= " + keyCode;
            BasePage.bd.ColumnNameToLower = false;
            String str = JsonConvert.SerializeObject(BasePage.bd.ExecuteTable(sql));
            BasePage.bd.ColumnNameToLower = true;
            List<Dictionary<String, Object>> data = JsonConvert.DeserializeObject<List<Dictionary<String, Object>>>(str);
            return BasePage.Json(ResultData.OK(data));

        }
        [HttpPost]
        public ActionResult Upload(string DirName)
        {
            #region + 变量
            //文件大小（字节数）
            long fileSize = 0;
            //重命名的文件名称
            string tempName = "";
            //物理路径+重命名的文件名称
            string fileName = "";
            //文件扩展名
            string extname = "";
            //虚拟路径
            string dir = "/UpFile/"+DirName;
            string path = HostingEnvironment.MapPath(dir);

       
            //获取提交的文件
            var file = Request.Files[0];
            //反馈对象     

       

            string _response  = "{\"code\": 1,\"msg\": \"服务器故障\",\"data\": {\"src\": \"\"}}"; ;
            #endregion
            #region + 服务器本地文件上传处理
            try
            {
                if (file != null && !string.IsNullOrEmpty(file.FileName))
                {
                    dir = DateTime.Now.ToString("yyyy-MM-dd");
                    if (!Directory.Exists(path + dir))
                    {
                        Directory.CreateDirectory(path + dir);
                    }
                    extname = file.FileName.Substring(file.FileName.LastIndexOf('.'), (file.FileName.Length - file.FileName.LastIndexOf('.')));
                    tempName = Guid.NewGuid().ToString().Substring(0, 6) + extname;
                    fileName = path + dir + "/" + tempName;
                    fileSize += file.ContentLength;
                    using (FileStream fs = System.IO.File.Create(fileName))
                    {
                        file.InputStream.CopyTo(fs);
                        fs.Flush();
                    }
                   
                    _response= "{\"code\": 0,\"msg\": \"服务器本地上传成功\",\"data\": {\"src\": \"" + dir + "/" + tempName + "\"}}";
                  
                }
            }
            catch (Exception ex)
            {
                
                _response = "{\"code\": 2,\"msg\": \"服务器本地上传失败 / n" + "错误信息：" + ex.Message+ "\",\"data\": {\"src\": \"\"}}";
            }
            #endregion
            return Json(_response);
        }
    }
}